package com.example.aigc_education.controller;

import cn.hutool.core.bean.BeanUtil;
//import com.agentsflex.llm.client.impl.SseClient;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.aigc_education.domain.Exam;
import com.example.aigc_education.domain.Notice;
import com.example.aigc_education.domain.UserCourse;
import com.example.aigc_education.domain.dto.ExamDTO;
import com.example.aigc_education.service.ExamService;
import com.example.aigc_education.service.NoticeService;
import com.example.aigc_education.service.UserCourseService;
import com.example.aigc_education.utils.ResultUtil;
import com.example.aigc_education.utils.SseServer;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/exam")
public class ExamController {


    @Resource
    private NoticeService noticeService;

    @Resource
    private ExamService examService;

    @Resource
    private UserCourseService userCourseService;

    /**
     * 批改作业（教师），前端批改后，调用此接口
     * @param paperId
     * @return
     */
    @PutMapping("/{paperId}/grade")
    public ResultUtil gradeExam(@PathVariable Long paperId) {
        return ResultUtil.success();
    }

    /**
     * 提交作业（学生）
     * 无提交记录表
     * @param examId 试卷ID
     * @return
     */
    @PutMapping("/{examId}/submit")
    public ResultUtil submitExam(@PathVariable Long examId) {
        Exam exam = examService.getById(examId);
        if (exam == null) {
            return ResultUtil.error("作业不存在");
        }
        if (exam.getExamEndTime().isBefore(LocalDateTime.now())) {
            return ResultUtil.error("作业已过期");
        }
        exam.setUpdateTime(LocalDateTime.now());
        examService.updateById(exam);
        return ResultUtil.success("提交成功");
    }



    /**
     * 作业发布（教师）
     * 作业发布成功后，通知消息给学生
     * @param courseId 课程ID
     * @param paperId 试卷ID
     * @return
     */
    @PostMapping("/{courseId}/{paperId}/students")
    public ResultUtil assignStudentsToPaper(@PathVariable Long courseId,
                                            @PathVariable Long paperId,
                                            @RequestBody ExamDTO examDTO) {
        // 1、根据课程ID获取学生列表
        List<Object> userIdList = userCourseService.listObjs(new LambdaQueryWrapper<UserCourse>().eq(UserCourse::getCourseId, courseId).select(UserCourse::getUserId));
        if (userIdList.isEmpty()) {
            return ResultUtil.error("该课程下没有学生");
        }
        // Object转Long
        List<Long> studentList = userIdList.stream()
                                            .map(userId -> Long.parseLong(userId.toString()))
                                            .collect(Collectors.toList());
        // 2、将学生列表和试卷ID关联，即发布作业,实例化exam
        studentList.forEach(studentId -> {
            Exam exam = BeanUtil.toBean(examDTO, Exam.class);
            exam.setCourseId(courseId);
            exam.setPaperId(paperId);
            exam.setUserId(studentId);
            examService.save(exam);

            Notice notice = new Notice();
            notice.setToUserId(studentId);
            notice.setContent(examDTO.getExamName());
            noticeService.save(notice);
        });
        // 3、通知消息给学生们
        SseServer.batchSendMessage(studentList, "您有新的作业");
        return ResultUtil.success("作业发布成功");
    }

    /**
     * 获取学生作业列表
     * @param courseId 课程ID
     * @return
     */
    @GetMapping("/{courseId}/students")
    public ResultUtil getStudentsExam(@PathVariable Long courseId) {
        List<Exam> examList = examService.list(new LambdaQueryWrapper<Exam>().eq(Exam::getCourseId, courseId));
        return ResultUtil.success(examList);
    }

    /**
     * 获取学生作业已过期列表
     * @param courseId 课程ID
     * @return
     */
    @GetMapping("/{courseId}/students/expired")
    public ResultUtil getStudentsExpiredExam(@PathVariable Long courseId) {
        List<Exam> examList = examService.list(new LambdaQueryWrapper<Exam>().eq(Exam::getCourseId, courseId).lt(Exam::getExamEndTime, System.currentTimeMillis()));
        return ResultUtil.success(examList);
    }

    /**
     * 获取学生作业未过期列表
     * @param courseId 课程ID
     * @return
     */
    @GetMapping("/{courseId}/students/notExpired")
    public ResultUtil getStudentsNotExpiredExam(@PathVariable Long courseId) {
        List<Exam> examList = examService.list(new LambdaQueryWrapper<Exam>().eq(Exam::getCourseId, courseId).ge(Exam::getExamEndTime, System.currentTimeMillis()));
        return ResultUtil.success(examList);
    }

    /**
     * 获取学生作业详情
     * @param examId 作业ID
     * @return
     */
    @GetMapping("/{examId}")
    public ResultUtil getExamDetail(@PathVariable Long examId) {
        Exam exam = examService.getById(examId);
        return ResultUtil.success(exam);
    }



}
